<template>
  <div class="">
    <!-- <mars-dialog :visible="true" right="10" top="10"> -->
    <graphic-layer-area ref="infoPanel" @onSaveData="saveData" @onPropEditInfoShow="onPropEditInfoShow" />
    <!-- </mars-dialog> -->
    <!-- <graphic-layer-state /> -->
    <!-- <div class="flex-center">
      <mars-button @click="onClickStartDraw">标记地点</mars-button>
    </div>
    <div class="flex-center">
      <mars-button @click="onPolygonDraw">标记区域</mars-button>
    </div> -->
    <!-- <div class="flex-center">
      <mars-button @click="saveData">保&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;存</mars-button>
    </div> -->
  </div>
</template>

<script lang="ts" setup>
/**
 * 公共组件：封装矢量图层操作
 * @copyright 火星科技 mars2d.cn
 * @author 火星渣渣灰 2022-08-31
 */
import { Ref, ref, reactive, onMounted, inject, provide } from 'vue';
import type { UnwrapRef } from 'vue';
import { $message } from '@mars/components/mars-ui/index';
import * as mapWorkMap from './widget-map';
import * as mars2d from 'mars2d';
import useLifecycle from './common/uses/use-lifecycle';
import GraphicLayerArea from "@mars/components/mars-sample/graphic-layer-area.vue"
const mapWork = mapWorkMap as any;
useLifecycle(mapWork);

const props = withDefaults(
  defineProps<{
    customEditor?: string;
    geoUrl?: string;
  }>(),
  {
    customEditor: '',
    geoUrl: '',
  }
);

interface FormState {
  enabledShowHide: boolean;
  enabledPopup: boolean;
  enabledTooltip: boolean;
  enabledRightMenu: boolean;
  enabledOpacity: boolean;
  opacity: number;
  enabledEdit: boolean;
  hasEdit: boolean;
  hasTable: boolean;
}

const formState: UnwrapRef<FormState> = reactive({
  enabledShowHide: true,
  enabledPopup: true,
  enabledTooltip: false,
  enabledRightMenu: false,
  enabledOpacity: true,
  opacity: 1,
  enabledEdit: true,
  hasEdit: true,
  hasTable: false,
});

onMounted(() => {
  // 恢复默认状态
  if (mapWork.eventTarget) {
    mapWork.eventTarget.on('defuatData', (item: any) => {
      formState.opacity = 1.0;
      formState.enabledShowHide = item.enabledShowHide;
      formState.enabledPopup = item.enabledPopup;
      formState.enabledTooltip = item.enabledTooltip;
      formState.enabledRightMenu = item.enabledRightMenu;
    });
  }

  setTimeout(() => {
    const layer = getManagerLayer();
    if (layer) {
      formState.enabledShowHide = layer.show;

      formState.enabledPopup = layer.hasPopup();
      formState.enabledTooltip = layer.hasTooltip();
      formState.enabledRightMenu = layer.hasContextMenu();
      formState.hasEdit = layer.isEditing;

      const graphics = layer.getGraphics();

      if (graphics.length > 0) {
        const lastgraphic = graphics[graphics.length - 1];
        formState.enabledOpacity = lastgraphic.hasOpacity;
      }

      formState.hasTable = graphics.length > 0;
    }
  }, 500);

  setTimeout(() => {
    // 导入图层信息
    onClickImpFile();
  }, 2000);
});

// 获取map.js中定义的需要管理的图层
function getManagerLayer() {
  if (mapWork.getManagerLayer) {
    return mapWork.getManagerLayer();
  }
  return mapWork.graphicLayer;
}
const onClickStartDraw = () => {
  mapWork.startDrawGraphic();
};
const onPolygonDraw = () => {
  mapWork.startDrawPolygonGraphic();
};
// 识别JSON
const onClickImpFile = async () => {
  // 获取配置
  const geojson = await mars2d.Util.fetchJson({ url: props.geoUrl });
  const graphicLayer = getManagerLayer();

  if (geojson.type === 'graphic' && geojson.data) {
    graphicLayer.addGraphic(geojson.data);
    graphicLayer.flyTo();
  } else {
    graphicLayer.loadGeoJSON(geojson, { flyTo: true });
  }
};
// 保存JSON
function getGeoJSON() {
  const graphicLayer = getManagerLayer();

  if (graphicLayer.length === 0) {
    $message('当前没有标注任何数据，无需保存！');
    return;
  }
  const geojson = graphicLayer.toGeoJSON();
  // mars2d.Util.downloadFile("矢量数据GeoJSON.json", JSON.stringify(geojson))
  return geojson;
};

function saveData() {
  const geojson = getGeoJSON()
  if (geojson) {
    emit('onSaveData', geojson);
  }
}
// 数据编辑属性面板 相关处理
onMounted(() => {
  const graphicLayer = getManagerLayer();

  // 矢量数据创建完成
  graphicLayer.on(mars2d.EventType.drawCreated, function (e) {
    if (formState.hasEdit || props.customEditor) {
      showEditor(e.graphic);
    }
  });
  // 修改了矢量数据
  graphicLayer.on('editStart editMovePoint editStyle editRemovePoint', function (e) {
    showEditor(e.graphic);
  });
});

const showEditor = (graphic: any) => {
  if (props.customEditor === graphic.type) {
    // disable('graphic-editor'); // 关闭属性面板
    emit('onStartEditor', {
      graphicId: graphic.id,
      graphicName: getGraphicName(graphic),
    });
    return;
  }

  emit('onStopEditor'); // 关闭参数调节面板

  const graphicLayer = getManagerLayer();
  graphicLayer.startEditing(graphic);
};

// 数据列表
interface GraphicTableItem {
  key: number;
  name: string;
}
const graphicDataList = ref<GraphicTableItem[]>([]);

onMounted(() => {
  const graphicLayer = getManagerLayer();
  initGraphicableData(graphicLayer);

  graphicLayer.on(mars2d.EventType.addGraphic, function (event) {
    const graphic = event.graphic;
    if (graphic.isPrivate) {
      return;
    }

    graphicDataList.value.push({
      key: graphic.id,
      name: getGraphicName(graphic),
    });
  });

  graphicLayer.on(mars2d.EventType.removeGraphic, function (event) {
    const graphicId = event.graphic.id;
    const idx = graphicDataList.value.findIndex((item) => item.key === graphicId);
    graphicDataList.value.splice(idx, 1);
  });
});

function initGraphicableData(graphicLayer) {
  const list = graphicLayer.graphics;
  for (let i = list.length - 1; i >= 0; i--) {
    const graphic = list[i];
    if (graphic.isPrivate) {
      continue;
    }
    graphicDataList.value.push({
      key: graphic.id,
      name: getGraphicName(graphic),
    });
  }
}

let graphicIndex = 0;
function getGraphicName(graphic) {
  if (graphic?.style?.label?.text) {
    return `${graphic.type} - ${graphic.style.label.text}`;
  }

  if (graphic.name) {
    return `${graphic.type} - ${graphic.name}`;
  }

  if (graphic?.attr?.remark) {
    return `${graphic.type} - ${graphic.attr.remark}`;
  }

  graphic.name = `未命名${++graphicIndex}`;
  return `${graphic.type} - ${graphic.name}`;
}

const onPropEditInfoShow = (graphic) => {
  emit('onPropEditInfoShow', graphic)
}

// 定义一个接口来描述子组件暴露出来的方法
interface GraphicLayerAreaMethods {
  updateGraphicDataList: (newStatus: any) => void;
}

const infoPanel: Ref<GraphicLayerAreaMethods | null> = ref(null);

const toUpdateGraphicMethod = (newStatus) => {
  if (infoPanel.value) {
    infoPanel.value.updateGraphicDataList(newStatus);
  }
};

defineExpose({ toUpdateGraphicMethod });

const emit = defineEmits(['onStartEditor', 'onStopEditor', 'onSaveData', 'onPropEditInfoShow']);
</script>

<style scoped lang="less">
.mars-pannel-item-label {
  width: auto;
}

.ant-input-number {
  width: 152px;
}

:deep(.ant-slider) {
  width: 80px;
}

:deep(.ant-table-pagination) {
  margin: 10px 0 1px 0 !important;
}

.data-list {
  width: 450px;
}

.widget-container {
  width: 50%;
}

.flex-center {
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
}
</style>
